const express = require('express');
const { UnauthorizedError } = require('express-jwt');
const expressJWT = require('express-jwt');
const jwt = require('jsonwebtoken');

const app = express();

const secretKey = 'asdfasdf';

const expressJWTMiddleware = expressJWT({
  secret: secretKey,
  algorithms: ['HS256'],
});

app.use('/api/admin', expressJWTMiddleware);

// 登录接口
app.post('/api/login', express.json(), (req, res) => {
  const { username, password } = req.body;
  if (username === 'mdmaodun' && password === 'qwe123') {
    const token = jwt.sign({ username }, secretKey, { expiresIn: '30s' });
    res.send({
      status: 200,
      msg: '登录成功',
      token,
    });
  } else {
    res.send({
      status: 400,
      msg: '账号或密码错误',
    });
  }
});

// 获取管理员信息
app.get('/api/admin/info', (req, res) => {
  res.send({
    status: 200,
    msg: 'ok',
    user: req.user,
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  if (err instanceof UnauthorizedError) {
    res.send({
      status: 401,
      msg: '无效的token',
    });
  } else {
    res.send({
      status: 500,
      msg: err.message,
    });
  }
});

app.listen(80, () => {
  console.log('running at http://localhost');
});
